package com.nabton.ndscollector.connection;

import com.nabton.ndscollector.connection.RequestInterface;
import com.nabton.ndscollector.connection.ClientHandler;


import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;


public class ConnectionManager
{
    private int port;
    private String host;
    private RequestInterface interfaceNDS;
    private Server server;
    
    public ConnectionManager(int port, String host, RequestInterface interfaceNDS)
    {
        this.port = port;
        this.host = host;
        this.interfaceNDS = interfaceNDS;
    }

    public boolean isServerAlive()
    {
        return server.isRunning();
    }
    
    public void startServer()
    {
        server = new Server();
        
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(port);
        connector.setHost(host);
        server.setConnectors(new Connector[]
        { connector });
        
        server.setHandler(new ClientHandler(this.interfaceNDS));
        
        try
        {
            server.start();
            //server.join();
        } 
        catch (Exception e)
        {
            e.printStackTrace();
        }
        
    }
    
    public void stopServer()
    {
        if(server.isRunning())
        {
            try
            {
                server.stop();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    
}
